<template>
  <el-card :body-style="{ padding: '20px' }">
    <el-button @click="goBack">返回</el-button>
    <h3>{{ survey.title }}</h3>
    <el-card header="问题集合">
      <el-form>
        <el-form-item label-position="top" :label="(idx+1) + '. ' + q.content" v-for="(q,idx) in qs" class="q">
          <br/>
          <template v-if="q.type === 'text'">
            <el-input v-model="answer[q.questionId]" type="textarea"></el-input>
          </template>
          <template v-if="q.type === 'multiple-choice'">
            <el-checkbox-group :model-value="getValue(q.questionId)" @change="e => setValue(e, q.questionId)">
              <el-checkbox v-for="item in (q.selectContent || '').split(',')" :label="item" :value="item" />
            </el-checkbox-group>
          </template>
          <template v-if="q.type === 'seleced'">
            <el-select v-model="answer[q.questionId]">
              <el-option v-for="item in (q.selectContent || '').split(',')" :label="item" :value="item"></el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="save" type="primary">提交保存</el-button>
      </template>
    </el-card>
  </el-card>
</template>

<script setup lang="ts">
import {defineProps, onMounted, reactive, ref} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import instance from "@/utils/http";
import CreateQForm from "@/components/CreateQForm.vue";
import Report from "@/components/Report.vue";
import {useAuthStore} from "@/stores/auth";
import {ElMessage} from "element-plus";

interface Survey {
  surveyId: number;
  amount: number;
  quantity: number;
  unitPrice: number;
  totalDiscountPrice: number;
  title: string;
  condition: string;
  content: string;
  creatorId: number;
  participantCount: number;
  createTime: string;
  endTime: string;
  status: string;
  description: string;
  createType:string
}

const answer = reactive<Record<number, string>>({})

const survey = ref<Survey>({
  surveyId: 0,
  amount: 0,
  quantity: 0,
  unitPrice: 0,
  totalDiscountPrice: 0,
  title: '',
  condition: '',
  content: '',
  creatorId: 0,
  participantCount: 0,
  createTime: '',
  endTime: '',
  status: 'ongoing',
  description: '',
  createType:"admin"
});

const qs = ref<{
  questionId: number
  surveyId: number
  content: string
  type: string
  selectContent: string
}[]>([])

const route = useRoute();
const router = useRouter();
const fetchAnswer = ref<{
  questionId: number
  answerId: number
  surveyId: number
  respondent: string
  content: string
  respondentId: number
  isValid: string
}[]>([])
const auth = useAuthStore()

const fetchSurvey = async (surveyId: number) => {
  try {
    const response = await instance.get(`/surveys/${surveyId}`);
    survey.value = response.data.data;
    const res = await instance.get('/questions/survey/'+surveyId)
    qs.value = res.data.data
    const re = await instance.get("/answers/survey/"+surveyId+"/"+auth.uid,)
    fetchAnswer.value = (re.data.data || [])
    fetchAnswer.value.map(item=>{
      answer[item.questionId] = item.content
    })
    console.log(answer)
  } catch (error) {
    console.error('无法加载调查详情');
  }
};

const setValue = (e:any, qId:number) => {
  answer[qId] = e.join(',')
}

const getValue = (qId:number) => {
  return answer[qId] ? answer[qId].split(',') : []
}

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  const surveyId = Number(route.params.surveyId);
  fetchSurvey(surveyId);
});

const save =  () => {
  if(fetchAnswer.value.length === 0){
    qs.value.map(async q=>{
      const re = await instance.post("/answers",{
        surveyId:survey.value.surveyId,
        questionId:q.questionId,
        respondent:auth.token,
        content: answer[ q.questionId],
        respondentId:auth.uid,
        isValid:false,
      })
    })
    ElMessage.success("提交成功")
  }else{
    qs.value.map(async q=>{
      const a = fetchAnswer.value.find(i=>i.questionId === q.questionId)
      if(!a){
        return
      }
      const re = await instance.put("/answers/"+a.answerId,{
        answerId:a.answerId,
        surveyId:a.surveyId,
        questionId:a.questionId,
        respondent:a.respondent,
        content: answer[q.questionId],
        respondentId:a.respondentId,
        isValid:a.isValid,
      })
      ElMessage.success("提交成功")
    })
  }
}
</script>

<style scoped>
.el-card {
  max-width: 1000px;
  margin: 0 auto;
}
</style>
